//
//  ViewController.swift
//  ScreenRecordingDemo
//
//  Created by huangkun on 2020/10/19.
//

import UIKit
import ReplayKit
import AVKit

let dirPath = HKSandboxFileHandle.sandboxPath(directory: .documents) + "/Replays"

class ViewController: UIViewController {
    
    @IBOutlet weak var timeLabel: UILabel!

    var timer:Timer?
    
    var count = 2
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // https://www.jianshu.com/p/ac916832a291
        
        
        navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: recordBtn),UIBarButtonItem(customView: seeFilesBtn)]
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: clearnBtn)
        addTimer()
    }
    
    func addTimer() {
        timer = Timer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        
        RunLoop.current.add(timer!, forMode: .common)
    }
    
    // MARK: -- lazy loading
    private lazy var recordBtn: UIButton = {
        let recordBtn = UIButton(type: .custom)
        recordBtn.setTitleColor(.red, for: .normal)
        recordBtn.setTitleColor(.red, for: .selected)
        recordBtn.setTitle("开始", for: .normal)
        recordBtn.setTitle("结束", for: .selected)
        recordBtn.addTarget(self, action: #selector(recordAction(sender:)), for: .touchUpInside)
        recordBtn.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
        return recordBtn
    }()
    
    private lazy var clearnBtn: UIButton = {
        let clearnBtn = UIButton(type: .custom)
        clearnBtn.setTitleColor(.red, for: .normal)
        clearnBtn.setTitleColor(.red, for: .selected)
        clearnBtn.setTitle("清除", for: .normal)
        clearnBtn.addTarget(self, action: #selector(clearnAction(sender:)), for: .touchUpInside)
        clearnBtn.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
        return clearnBtn
    }()
    
    private lazy var seeFilesBtn: UIButton = {
        let seeFilesBtn = UIButton(type: .custom)
        seeFilesBtn.setTitleColor(.red, for: .normal)
        seeFilesBtn.setTitleColor(.red, for: .selected)
        seeFilesBtn.setTitle("文件", for: .normal)
        seeFilesBtn.addTarget(self, action: #selector(seeFilesAction(sender:)), for: .touchUpInside)
        seeFilesBtn.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
        return seeFilesBtn
    }()

}

extension ViewController {
    
    @IBAction func playAction(_ sender: Any) {
        if let url = URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") {
            let vc = AVPlayerViewController()
            vc.player = AVPlayer(url: url)
            present(vc, animated: true, completion: nil)
        }
    }
    
    @IBAction func pauseAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if #available(iOS 11.0, *) {
            ScreenRecordManager.share.isPaused = sender.isSelected
        } else {
            // Fallback on earlier versions
        }
    }
    
    @IBAction func audioMuteAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if #available(iOS 11.0, *) {
            ScreenRecordManager.share.isRecordAudio = !sender.isSelected
        } else {
            // Fallback on earlier versions
        }
    }
    
    @objc private func timerAction() {
        let date = Date()
        let fomatter = DateFormatter()
        fomatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        timeLabel.text = fomatter.string(from: date)
    }
    
    @objc private func recordAction(sender:UIButton) {
        sender.isSelected = !sender.isSelected
        
        if sender.isSelected {
            // 开始录屏
            startRecord()
        } else {
            // 结束录屏
            endRecord()
        }
    }
    
    @objc private func clearnAction(sender:UIButton) {
        try? FileManager.default.removeItem(atPath: dirPath)
    }
    
    @objc private func seeFilesAction(sender:UIButton) {
        let vc = FilesTableViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    /// 开始录屏
    private func startRecord() {
        if #available(iOS 11.0, *) {
            if !ScreenRecordManager.share.isRecording {

                do {
                    try HKSandboxFileHandle.creatDirectory(path: dirPath)
                    let filePath = dirPath + "/\(UUID().uuidString.replacingOccurrences(of: "-", with: "")).mp4"
                    ScreenRecordManager.share.startRecord(filePath: filePath) { (error) in
                        print("start record error = \(error)")
                    }
                } catch let error {
                    print("error = \(error)")
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }
    
    /// 结束录屏
    private func endRecord() {
        if #available(iOS 11.0, *) {
            ScreenRecordManager.share.stopRecord { (error) in
                print("stop record error = \(error)")
            }
        } else {
            // Fallback on earlier versions
        }
    }
}

// MARK: -- iOS9
extension ViewController: RPPreviewViewControllerDelegate {
    func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
        print("=====")
    }
    
    func previewController(_ previewController: RPPreviewViewController, didFinishWithActivityTypes activityTypes: Set<String>) {
        print("+++++ = \(activityTypes)")
        previewController.dismiss(animated: true, completion: nil)
    }
}


 
